import React, { Component } from 'react'
import './table.scss'

export default class Table extends Component {
  constructor (props) {
    super(props)
    const header = []
    this.props.children.forEach(u => {
      header.push({
        keyName: u.props.keyName,
        label: u.props.label,
        renderFn: u.props.renderFn
      })
    })
    this.state = {
      header
    }
  }
  render () {
    return (
      <table className="tbcTable">
        <thead>
        <tr>
        {
          this.state.header.map(u => {
            return (
              <td className="tbcTableHead" key={u.label}>{u.label}</td>
            )
          })
        }
        </tr>
        </thead>
        <tbody>
          {
            this.props.tableData.map((u, index) => {
              return (
                <tr key={index}>
                  {
                    this.state.header.map((k, index2) => {
                      if (k.renderFn) {
                        return (<td key={index2} className="tbcTableTd">{ k.renderFn(u) }</td>)
                      } else {
                        return(<td key={index2} className="tbcTableTd">{ u[k.keyName] }</td>)
                      }
                    })
                  }
                </tr>
              )
            })
          }
        </tbody>
      </table>
    )
  }
}